package cn.gcBlock.rest;

import cn.gcBlock.service.BlockNodeService;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.fastjson.JSON;
import cn.gcBlock.exception.BadRequestException;
import cn.gcBlock.dto.NodeDTO;
import cn.gcBlock.utils.TemplateUtils;
import cn.gcBlock.utils.XhtmlToImageUtils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Api(tags = "区块链资料下载接口")
@RestController
@RequestMapping
public class DownLoadController {
    @Resource
    BlockNodeService blockNodeService;

    @ApiOperation(value = "下载所有账单")

    @RequestMapping(name = "下载所有账单", value = "/download", method = RequestMethod.GET)
    public void down(HttpServletResponse response) throws IOException {
        List<NodeDTO> result = blockNodeService.findAll();
        String fileString = new String(JSON.toJSONString(result));
        //设置文件MIME类型
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        //设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;fileName=blockData.txt");
        response.addHeader("Content-Length", "" + fileString.getBytes().length);
        OutputStream out = response.getOutputStream();
        //写文件
        out.write(fileString.getBytes());
        out.flush();
        out.close();
    }

    @ApiOperation(value = "下载所有账单")

    @RequestMapping(name = "下载所有账单", value = "/signature/pdf", method = RequestMethod.GET)
    public ResponseEntity<byte[]> signature(HttpServletRequest request) throws UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        String signature = request.getParameter("signature");
        if (StringUtils.isEmpty(signature)) {
            throw new BadRequestException("签名不存在！");
        }
        NodeDTO nodeDTO = blockNodeService.findById(signature);
        if (nodeDTO == null) {
            throw new BadRequestException("区块不存在！");
        }


        String filename = new String((signature + ".pdf").getBytes("gbk"), "iso8859-1");
        headers.add("Content-Disposition", "attachment;filename=" + filename);
        //headers.add("Content-type","application/pdf");
        // 模板路径
        String templatePath = new ClassPathResource("/pdf/signature.pdf").getPath();
        // 生成的新文件路径
        PdfReader reader;
        ByteArrayOutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper;
        try {
            out = new ByteArrayOutputStream();// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            form.setField("signature", nodeDTO.getSignature());
            form.setField("publicKey", nodeDTO.getPublicKey());
            form.setField("toPublicKey", nodeDTO.getToPublicKey());
            form.setField("coin", String.valueOf(nodeDTO.getCoin()));
            form.setField("timestamp", String.valueOf(nodeDTO.getTimestamp()));
            form.setField("blockName", nodeDTO.getBlockName());
            form.setField("remark", nodeDTO.getRemark());
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage1 = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            PdfImportedPage importPage2 = copy.getImportedPage(new PdfReader(bos.toByteArray()), 2);
            copy.addPage(importPage1);
            copy.addPage(importPage2);
            doc.close();
        } catch (IOException e) {
            System.out.println(1);
        } catch (DocumentException e) {
            System.out.println(2);
        }
        ResponseEntity response = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        return response;
    }

    @GetMapping("/success")
    public ModelAndView sucTest() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pdf");
        return modelAndView;
    }

    @RequestMapping("pdf")
    public void pdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream out = response.getOutputStream();
        Context context = new Context();
        context.setVariable("name", "world");
        String html = TemplateUtils.process("pdf.html", context);
        response.setContentType("application/pdf");
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        // 携带图片,将图片标签转换为itext自己的图片对象
        // 字体名称要大写，否则可能找不到
        fontResolver.addFont("font/simsun.ttc", "Identity-H", false);
        renderer.setDocumentFromString(html, "http://localhost:8088/");
        renderer.layout();
        renderer.createPDF(out);
        // 解决中文支持问题
        out.flush();
        out.close();
    }

    @RequestMapping("newPdf")
    public void newPdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream out = response.getOutputStream();
        Context context = new Context();
        context.setVariable("name", "world");
        String html = TemplateUtils.process("pdf.html", context);
        PdfRendererBuilder builder = new PdfRendererBuilder();
        builder.useFastMode();
        builder.withHtmlContent(html,"http://localhost:8088/");
                builder.toStream(out);
        builder.run();
    }
    @RequestMapping("img")
    public void img(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream out = response.getOutputStream();
        Context context = new Context();
        context.setVariable("name", "world");
        String html = TemplateUtils.process("pdf.html", context);
        int widthImage = 1600;
        int heightImage = 1000;
        String inputFileName = "source.xhtml";
        String outFileName = "image.jpg";
        XhtmlToImageUtils.convertXhtmlToImage(html,inputFileName,out,widthImage,heightImage);
        out.flush();
        out.close();
    }
}
